<template>
  <div class="player" v-show="playList.length">
    <transition name="noraml">
      <div class="normal-player" v-show="fullScreen">
        <div class="background">
          <img :src="currentSong.image" width="100%" height="100%">
        </div>
        <div class="top">
          <div class="back" @click.stop="toMiniStyle"><i class="icon-back"></i></div>
          <h1 class="title" v-html="currentSong.name"></h1>
          <h2 class="sub-title" v-html="currentSong.singer"></h2>
        </div>
        <div class="middle" @touchstart.prevent="middleTouchStart"
             @touchmove.prevent="middleTouchMove"
             @touchend="middleTouchEnd">
          <div class="middle-l" ref="middleL">
            <div class="cd-wrapper" ref="cdWrapper">
              <div class="cd" :class="cdCls">
                <img class="image" :src="currentSong.image">
              </div>
            </div>
            <div class="playing-lrc-wrap">
              <div class="playing-lrc">{{playingLrc}}</div>
            </div>
          </div>
          <scroll class="middle-r" ref="lyricList" :data="currentLrc && currentLrc.lines">
            <div class="lyric-wrapper">
              <div v-if="currentLrc">
                <p ref="lyricLine"
                   class="text"
                   :class="{'current': currentLineNum ===index}"
                   v-for="(line,index) in currentLrc.lines">{{line.txt}}</p>
              </div>
            </div>
          </scroll>

        </div>
        <div class="bottom">
          <div class="dot-wrap">
            <span class="dot" :class="{'active':currentShow==='cd'}"></span>
            <span class="dot" :class="{'active':currentShow==='lyric'}"></span>
          </div>
          <div class="progress-wrap">
            <span class="time time-l">{{fmtTime(currentTime)}}</span>
            <div class="progress-bar-wrap">
              <progress-bar :percent="percent" @percentChange="changePercent"></progress-bar>
            </div>
            <span class="time time-r">{{fmtTime(currentSong.duration)}}</span>
          </div>
          <div class="operators-wrap">
            <div class="icon i-left">
              <i :class="modeIcon" @click.stop="changeMode"></i>
            </div>
            <div class="icon i-left" :class="disableCls">
              <i class="icon-prev" @click.stop="prevSong"></i>
            </div>
            <div class="icon i-center" :class="disableCls">
              <i :class="playIcon" @click.stop="togglePlay"></i>
            </div>
            <div class="icon i-right" :class="disableCls">
              <i class="icon-next" @click.stop="nextSong"></i>
            </div>
            <div class="icon i-right" @click.stop="toggleFavorite(currentSong)">
              <i :class="getFavoriteIcon(currentSong)"></i>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <transition name="mini">
      <div class="mini-player" v-show="!fullScreen" @click.stop="toFullScreenStyle">
        <div class="icon">
          <img width="40" height="40" :src="currentSong.image">
        </div>
        <div class="text">
          <h3 class="name" v-html="currentSong.name"></h3>
          <p class="desc" v-html="currentSong.singer"></p>
        </div>
        <div class="control">
          <progress-circle :radius="radius" :percent="percent">
            <i :class="miniPlayIcon" class="icon-mini" @click.stop="togglePlay"></i>
          </progress-circle>
        </div>
        <div class="control" @click.stop="showPlaylist">
          <i class="icon-playlist"></i>
        </div>
      </div>
    </transition>
    <playlist ref="playlist"></playlist>
    <audio :src="currentSong.url" ref="audio" @play="audioReady" @error="audioError" @timeupdate="updateTime"
           @ended="audioEnd"></audio>
  </div>
</template>

<script>
  import ProgressBar from '../base/progress-bar/progress-bar.vue';
  import ProgressCircle from '../base/progress-circle/progress-circle.vue';
  import Scroll from '../base/scroll/scroll.vue';
  import Playlist from '../playlist/playlist.vue';
  import {mapGetters, mapActions, mapMutations} from 'vuex';
  import {playMode} from 'common/js/config.js';
  import LrcParser from 'lyric-parser';
  import {prefixStyle} from 'common/js/dom.js';
  import {playerMixin} from 'common/js/mixin.js';

  const transform = prefixStyle('transform');
  const transitionDuration = prefixStyle('transitionDuration');
  export default {
    mixins: [playerMixin],
    components: {ProgressBar, ProgressCircle, Scroll, Playlist},
    data () {
      return {
        songReady: false,
        currentTime: 0,
        radius: 32,
        currentLrc: null,
        playingLrc: '',
        currentLineNum: 0,
        currentShow: 'cd',
        touch: {}
      };
    },
    computed: {
      percent () {
        return this.currentTime / this.currentSong.duration;
      },
      playIcon () {
        return this.playing ? 'icon-pause' : 'icon-play';
      },
      miniPlayIcon () {
        return this.playing ? 'icon-pause-mini' : 'icon-play-mini';
      },
      cdCls () {
        return this.playing ? 'play' : 'play pause';
      },
      disableCls () {
        return this.songReady ? '' : 'disable';
      },
      ...mapGetters([
        'fullScreen',
        'playing'
      ])
    },
    watch: {
      currentSong (newSong, oldSong) {
        if (!newSong.id) {
          return;
        }
        if (newSong.id === oldSong.id) {
          return;
        }
        if (this.currentLrc) {
          this.currentLrc.stop();
          this.currentTime = 0;
          this.playingLrc = '';
          this.currentLineNum = 0;
        }
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.$refs.audio.play();
          this.getLrc();
        }, 1000);
      },
      playing (newV) {
        const audio = this.$refs.audio;
        this.$nextTick(() => {
          newV ? audio.play() : audio.pause();
        });
      }
    },
    methods: {
      toMiniStyle () {
        this.setFullScreen(false);
      },
      toFullScreenStyle () {
        this.setFullScreen(true);
      },
      togglePlay () {
        if (!this.songReady) {
          return;
        }
        this.setPlayingState(!this.playing);
        if (this.currentLrc) {
          this.currentLrc.togglePlay();
        }
      },
      nextSong () {
        if (!this.songReady) {
          return;
        }
        this.songReady = false;
        if (this.playList.length === 1) {
          this.loop();
          return;
        }
        let index = this.currentIndex + 1;
        if (index >= this.playList.length) {
          index = 0;
        }
        this.setSongIndex(index);
        if (!this.playing) {
          this.togglePlay();
        }
      },
      prevSong () {
        if (!this.songReady) {
          return;
        }
        this.songReady = false;
        if (this.playList.length === 1) {
          this.loop();
          return;
        }
        let index = this.currentIndex - 1;
        if (index === -1) {
          index = this.playList.length - 1;
        }
        this.setSongIndex(index);
        if (!this.playing) {
          this.togglePlay();
        }
      },
      loop () {
        this.$refs.audio.currentTime = 0;
        this.$refs.audio.play();
        if (this.currentLrc) {
          this.currentLrc.seek(0);
        }
      },
      audioReady () {
        this.songReady = true;
        this.savePlayHistory(this.currentSong);
      },
      audioError () {
        this.songReady = true;
      },
      audioEnd () {
        if (this.mode === playMode.loop) {
          this.loop();
        } else {
          this.nextSong();
        }
      },
      changePercent (percent) {
        let newTime = this.currentSong.duration * percent;
        this.$refs.audio.currentTime = newTime;
        if (!this.playing) {
          this.togglePlay();
        }
        if (this.currentLrc) {
          this.currentLrc.seek(newTime * 1000);
        }
      },
      updateTime (e) {
        this.currentTime = e.target.currentTime;
      },
      fmtTime (intval) {
        let m = intval / 60 | 0;
        let s = intval % 60 | 0;
        m = ('0' + m).slice(-2);
        s = ('0' + s).slice(-2);
        return `${m}:${s}`;
      },
      getLrc () {
        this.currentSong.getLrc().then(res => {
          this.currentLrc = new LrcParser(res, this.handleLrc);
//          console.log(this.currentLrc);
          if (this.playing) {
            this.currentLrc.play();
          }
        }).catch((e) => {
          this.currentLrc = null;
          this.playingLrc = '';
          this.currentLineNum = 0;
        });
      },
      handleLrc ({lineNum, txt}) {
//        console.log(lineNum);
        if (lineNum > 5) {
          let lineEl = this.$refs.lyricLine[lineNum - 5];
          this.$refs.lyricList.scrollToElement(lineEl, 1000);
        } else {
          this.$refs.lyricList.scrollTo(0, 0, 1000);
        }
        this.currentLineNum = lineNum;
        this.playingLrc = txt;
      },

      middleTouchStart (e) {
        this.touch.initState = true;
        this.touch.startX = e.touches[0].pageX;
        this.touch.startY = e.touches[0].pageY;
      },
      middleTouchMove (e) {
        if (!this.touch.initState) {
          return;
        }
        const deltX = e.touches[0].pageX - this.touch.startX;
        const deltY = e.touches[0].pageY - this.touch.startY;
        if (Math.abs(deltX) < Math.abs(deltY)) {
          return;
        }
        // console.log(deltX);
        const left = this.currentShow === 'cd' ? 0 : -window.innerWidth;
        const offsetWidth = Math.min(0, Math.max(left + deltX, -window.innerWidth));
        this.touch.percent = Math.abs(offsetWidth / window.innerWidth);
        this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`;
        this.$refs.lyricList.$el.style[transitionDuration] = 0;
        this.$refs.middleL.style.opacity = 1 - this.touch.percent;
        this.$refs.middleL.style[transitionDuration] = 0;
      },
      showPlaylist () {
        this.$refs.playlist.show();
      },
      middleTouchEnd (e) {
        let offsetWidth = null;
        let opacity = null;
        if (this.currentShow === 'cd') {
          if (this.touch.percent > 0.1) {
            offsetWidth = -window.innerWidth;
            opacity = 0;
            this.currentShow = 'lyric';
          } else {
            offsetWidth = 0;
            opacity = 1;
          }
        } else {
          if (this.touch.percent < 0.9) {
            offsetWidth = 0;
            opacity = 1;
            this.currentShow = 'cd';
          } else {
            offsetWidth = -window.innerWidth;
            opacity = 0;
          }
        }
        const time = 300;
        this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`;
        this.$refs.lyricList.$el.style[transitionDuration] = `${time}ms`;
        this.$refs.middleL.style.opacity = opacity;
        this.$refs.middleL.style[transitionDuration] = `${time}ms`;
        this.touch.initiated = false;
      },
      ...mapMutations({
        setFullScreen: 'SET_FULLSCREEN'
      }),
      ...mapActions([
        'savePlayHistory'
      ])
    },
    created () {
//      console.log(this.currentSong);
    }
  };
</script>

<style lang="less">
  @import "~common/css/variable.less";
  @import "~common/css/mixin.less";

  .player {
    .normal-player {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: @color-background;
      z-index: 150;
      .background {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
        opacity: 0.5;
        filter: blur(20px);
      }
      .top {
        position: relative;
        margin-bottom: 25px;
        .back {
          position: absolute;
          top: 0;
          left: 0;
          z-index: 50;
          .icon-back {
            display: block;
            padding: 9px;
            font-size: @font-size-large-x;
            color: @color-theme;
            transform: rotate(-90deg);
          }
        }
        .title {
          width: 70%;
          margin: 0 auto;
          text-align: center;
          line-height: 40px;
          font-size: @font-size-large;
          color: @color-text;
          .no-wrap;
        }
        .sub-title {
          line-height: 20px;
          text-align: center;
          font-size: @font-size-medium;
          color: @color-text;
        }
      }
      .middle {
        position: fixed;
        width: 100%;
        top: 80px;
        bottom: 170px;
        white-space: nowrap;
        font-size: 0;
        .middle-l {
          position: relative;
          display: inline-block;
          vertical-align: top;
          width: 100%;
          height: 0;
          padding-top: 80%;
          .cd-wrapper {
            position: absolute;
            left: 10%;
            top: 0;
            width: 80%;
            height: 100%;
            .cd {
              width: 100%;
              height: 100%;
              box-sizing: border-box;
              border: 10px solid rgba(255, 255, 255, 0.1);
              border-radius: 50%;
              &.play {
                animation: playAnimate 20s linear infinite;
              }
              &.pause {
                animation: paused;
              }
              .image {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                border-radius: 50%;
              }
            }
          }
          .playing-lrc-wrap {
            width: 80%;
            margin: 30px auto 0 auto;
            overflow: hidden;
            text-align: center;
            .playing-lrc {
              height: 20px;
              line-height: 20px;
              font-size: @font-size-medium;
              color: @color-text-l;
            }
          }
        }
        .middle-r {
          display: inline-block;
          vertical-align: top;
          width: 100%;
          height: 100%;
          overflow: hidden;
          .lyric-wrapper {
            width: 80%;
            margin: 0 auto;
            overflow: hidden;
            text-align: center;
            .text {
              line-height: 32px;
              color: @color-text-l;
              font-size: @font-size-medium;
              &.current {
                color: @color-text;
              }
            }
          }
        }
      }
      .bottom {
        position: absolute;
        bottom: 50px;
        width: 100%;
        .dot-wrap {
          text-align: center;
          font-size: 0;
          .dot {
            display: inline-block;
            vertical-align: middle;
            margin: 0 4px;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: @color-text-l;
            &.active {
              width: 20px;
              border-radius: 5px;
              background: @color-text-ll;
            }
          }
        }
        .progress-wrap {
          display: flex;
          align-items: center;
          width: 80%;
          margin: 0 auto;
          padding: 10px 0;
          .time {
            flex: 0 0 30px;
            width: 30px;
            line-height: 30px;
            font-size: @font-size-small;
            color: @color-text;
            &.time-l {
              text-align: left;
            }
            &.time-r {
              text-align: right;
            }
          }
          .progress-bar-wrap {
            flex: 1;
            padding: 0 5px;
          }
        }
        .operators-wrap {
          display: flex;
          align-items: center;
          .icon {
            flex: 1;
            color: @color-theme;
            &.disable {
              color: @color-theme-d;
            }
            i {
              font-size: 30px;
            }
          }
          .i-left {
            text-align: right;
          }
          .i-center {
            padding: 0 20px;
            text-align: center;
            i {
              font-size: 40px;
            }
          }
          .i-right {
            text-align: left;
          }
          .icon-favorite {
            color: @color-sub-theme;
          }
        }
      }
      &.normal-enter-active, &.normal-leave-active {
        transition: all 0.4s;
        .top, .bottom {
          transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32)
        }
      }
      &.normal-enter, &.normal-leave-to {
        opacity: 0;
        .top {
          transform: translate3d(0, -100px, 0);
        }
        .bottom {
          transform: translate3d(0, 100px, 0);
        }
      }
    }
    .mini-player {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      height: 60px;
      display: flex;
      align-items: center;
      background: @color-highlight-background;
      z-index: 180;
      &.mini-enter-active, &.mini-leave-active {
        transition: all 0.4s;
      }
      &.mini-enter, &.mini-leave-to {
        opacity: 0;
      }
      .icon {
        flex: 0 0 40px;
        width: 40px;
        padding: 0 10px 0 20px;
        img {
          border-radius: 50%;
        }
      }
      .text {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        line-height: 20px;
        overflow: hidden;
        .name {
          margin-top: 2px;
          .no-wrap();
          font-size: @font-size-medium;
          color: @color-text;
        }
        .desc {
          .no-wrap();
          font-size: @font-size-small;
          color: @color-text;
        }
      }
      .control {
        flex: 0 0 30px;
        width: 30px;
        padding: 0 10px;
        .icon-play-mini, .icon-pause-mini, .icon-playlist {
          font-size: 30px;
          color: @color-theme-d;
        }
        .icon-mini {
          position: absolute;
          left: 0;
          top: 0;
          font-size: 32px;
        }
      }
    }
  }

  @keyframes playAnimate {
    0% {
      transform: rotate(0);
    }
    100% {
      transform: rotate(360deg);
    }
  }
</style>
